package com.alibaba.citrus.cr.unified.inventory.facade.service;


import com.alibaba.fastjson.JSONObject;
import com.alibaba.lattice2.epoch.db.service.CustomSequenceAccessor;
import com.alibaba.lattice2.epoch.sdk.model.Result;
import com.alibaba.lattice2.epoch.sdk.oss.EpochOssService;
import com.alibaba.lattice2.epoch.user.service.EpochLoginUserService;
import com.epoch.app.bcorder.service.BaseDataService;
import com.epoch.app.crunifiedinventory.model.dto.*;
import com.epoch.app.crunifiedinventory.model.enums.SurplusInventoryStatus;
import com.epoch.app.crunifiedinventory.ouisurplusinventoryorder.dto.LoadResponse;
import com.epoch.app.crunifiedinventory.ouisurplusinventoryorder.service.OuiSurplusInventoryOrderService;
import com.epoch.app.crunifiedinventory.ouisurplusinventoryorderdetail.service.OuiSurplusInventoryOrderDetailService;
import com.epoch.app.crunifiedinventory.surplusinventorywrite.service.SurplusInventoryWriteService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.UUID;


/**
 * @author Chen.mu
 * @date 2021/11/8
 */
@Component
public class SurplusInventoryWriteServiceImpl implements SurplusInventoryWriteService {
    @Autowired
    OuiSurplusInventoryOrderService ouiSurplusInventoryOrderService;
    @Autowired
    OuiSurplusInventoryOrderDetailService ouiSurplusInventoryOrderDetailService;
    @Autowired
    BaseDataService baseDataService;
    @Autowired
    EpochOssService epochOssService;
    @Autowired
    EpochLoginUserService epochLoginUserService;
    @Autowired
    CustomSequenceAccessor customSequenceAccessor;

    @Override
    public Result<String> create(SurplusInventoryCreateRequest surplusInventoryCreateRequest) {
//        String ouiOrderId ="RAO" +customSequenceAccessor.getNextStringSequence("ots_unified_inventory","SURPLUS_INVENTORY");
        String ouiOrderId ="RAO" +customSequenceAccessor.getNextStringSequence("cr_unified_inventory","SURPLUS_INVENTORY");
        //审批人对象
            ouiSurplusInventoryOrderService.create(
                    OuiSurplusInventoryOrderCreateRequest.builder()
                            .siOrderId(ouiOrderId)
                            .applyDate(surplusInventoryCreateRequest.getApplyDate())
                            .encrypLevel(surplusInventoryCreateRequest.getEncrypLevel())
                            .intermediary(surplusInventoryCreateRequest.getIntermediary())
                            .phone(surplusInventoryCreateRequest.getPhone())
                            .remark(surplusInventoryCreateRequest.getRemark())
                            .title(surplusInventoryCreateRequest.getTitle())
                            .receiveGroupId(surplusInventoryCreateRequest.getReceiveGroupId())
                            .submitGroupId(surplusInventoryCreateRequest.getSubmitGroupId())
                            .status(1)
                            .imgUrl(JSONObject.toJSONString(surplusInventoryCreateRequest.getFiles()))
                            .auditors(JSONObject.toJSONString(getAudotorResp(surplusInventoryCreateRequest)))
                            .bizUnitId(surplusInventoryCreateRequest.getBizUnitId())
                            .build());
            if(surplusInventoryCreateRequest.getGoodsList()!=null&&surplusInventoryCreateRequest.getGoodsList().size()>0) {
                for (SurplusInventoryGoodsCreateRequest child : surplusInventoryCreateRequest.getGoodsList()) {
                    String ouiSubOrderId = "SRAO" + customSequenceAccessor.getNextStringSequence("ots_unified_inventory", "SURPLUS_INVENTORY");
                    BigDecimal preFee=(child.getPreFee()==null?new BigDecimal(0):child.getPreFee());
                    BigDecimal price= (child.getPrice()==null?new BigDecimal(0):child.getPrice());
                    ouiSurplusInventoryOrderDetailService.create(OuiSurplusInventoryOrderDetailCreateRequest.builder()
                            .dom(child.getDom())
                            .siOrderId(ouiOrderId)
                            .siSubOrderId(ouiSubOrderId)
                            .endPoint(child.getEndPoint())
                            .exchangeRate(child.getExchangeRate())
                            .remark(child.getRemark())
                            .quantity(child.getQuantity())
                            .preFee(preFee.multiply(new BigDecimal(1000)))
                            .price(price.multiply(new BigDecimal(1000)))
                            .scItemId(child.getScItemId())
                            .status(1).build());
                }
            }
            return Result.success(ouiOrderId);
        }

    @Override
    public Result<Void> update(SurplusInventoryCreateRequest surplusInventoryCreateRequest) {
        ouiSurplusInventoryOrderService.update(
                OuiSurplusInventoryOrderCreateRequest.builder()
                        .siOrderId(surplusInventoryCreateRequest.getSiOrderId())
                        .applyDate(surplusInventoryCreateRequest.getApplyDate())
                        .encrypLevel(surplusInventoryCreateRequest.getEncrypLevel())
                        .intermediary(surplusInventoryCreateRequest.getIntermediary())
                        .phone(surplusInventoryCreateRequest.getPhone())
                        .remark(surplusInventoryCreateRequest.getRemark())
                        .title(surplusInventoryCreateRequest.getTitle())
                        .receiveGroupId(surplusInventoryCreateRequest.getReceiveGroupId())
                        .submitGroupId(surplusInventoryCreateRequest.getSubmitGroupId())
                        .status(SurplusInventoryStatus.DRAFT.getValue())
                        .imgUrl(JSONObject.toJSONString(surplusInventoryCreateRequest.getFiles()))
                        .auditors(JSONObject.toJSONString(getAudotorResp(surplusInventoryCreateRequest)))
                        .bizUnitId(surplusInventoryCreateRequest.getBizUnitId())
                        .build());
        if(surplusInventoryCreateRequest!=null&&surplusInventoryCreateRequest.getGoodsList().size()>0) {
            OuiSurplusInventoryOrderDetailLoadListVO requet = new OuiSurplusInventoryOrderDetailLoadListVO();
            requet.setSiOrderId(surplusInventoryCreateRequest.getSiOrderId());
            Result<List<SurplusInventoryDetailResponse>> detailList = ouiSurplusInventoryOrderDetailService.loadList(requet);
            //子单再变更时， 全都删除了 重新创建
            detailList.getResult().forEach(x -> {
                ouiSurplusInventoryOrderDetailService.delete(SurplusInventoryGoodsCreateRequest.builder().siSubOrderId(x.getSiSubOrderId()).build());
            });
            for (SurplusInventoryGoodsCreateRequest child : surplusInventoryCreateRequest.getGoodsList()) {
                String ouiSubOrderId = "SPOI" + UUID.randomUUID();
                BigDecimal preFee=(child.getPreFee()==null?new BigDecimal(0):child.getPreFee());
                BigDecimal price= (child.getPrice()==null?new BigDecimal(0):child.getPrice());
                ouiSurplusInventoryOrderDetailService.create(OuiSurplusInventoryOrderDetailCreateRequest.builder()
                        .dom(child.getDom())
                        .siOrderId(surplusInventoryCreateRequest.getSiOrderId())
                        .siSubOrderId(ouiSubOrderId)
                        .endPoint(child.getEndPoint())
                        .exchangeRate(child.getExchangeRate())
                        .remark(child.getRemark())
                        .quantity(child.getQuantity())
                        .preFee(preFee.multiply(new BigDecimal(1000)))
                        .price(price.multiply(new BigDecimal(1000)))
                        .scItemId(child.getScItemId())
                        .status(1).build());
            }
        }
        return Result.success(null);
    }

    @Override
    public Result<Void> updateStatus(SurplusInventoryCreateRequest surplusInventoryCreateRequest) {
        LoadResponse loadResponse=   ouiSurplusInventoryOrderService.load(SurplusOrderQueryRequest.newSurplusOrderQueryRequestBuilder().siOrderId(surplusInventoryCreateRequest.getSiOrderId()).build());
        if(loadResponse.getResult()!=null) {
            SurplusInventoryResponse oldOrder=loadResponse.getResult();
//            switch (oldOrder.getStatus()){
//                case 1:
//                    if(surplusInventoryCreateRequest.getStatus().intValue()!=SurplusInventoryStatus.WAIT_EXAMINE.getValue().intValue()){
//                        throw new FacadeException("OTS-03-004-15-01");
//                    }
//                    break;
//                case 2:
//                    if(!(surplusInventoryCreateRequest.getStatus().intValue()==SurplusInventoryStatus.EXAMINE_REJECT.getValue().intValue()
//                            ||surplusInventoryCreateRequest.getStatus().intValue()==SurplusInventoryStatus.EXAMINE_PASS.getValue()||
//                            surplusInventoryCreateRequest.getStatus().intValue()==SurplusInventoryStatus.EXAINING.getValue())){
//                        throw new FacadeException("OTS-03-004-15-02");
//                    }
//                    break;
//                case 3:
//                case 4:
//                case -1:
//                    return Result.success(null);
//            }
             OuiSurplusInventoryOrderCreateRequest.OuiSurplusInventoryOrderCreateRequestBuilder requestBuilder= OuiSurplusInventoryOrderCreateRequest.builder()
                    .siOrderId(surplusInventoryCreateRequest.getSiOrderId())
                    .status(surplusInventoryCreateRequest.getStatus())
                    .flowId(surplusInventoryCreateRequest.getFlowId())
                    ;
            if(surplusInventoryCreateRequest.getStatus().intValue()==SurplusInventoryStatus.WAIT_EXAMINE.getValue().intValue()||
                    surplusInventoryCreateRequest.getStatus().intValue()==SurplusInventoryStatus.EXAINING.getValue().intValue()){
                requestBuilder=requestBuilder.gmtCommit(new Date());
            }
            ouiSurplusInventoryOrderService.update(
                    requestBuilder.build()
                   );
        }
        return Result.success(null);
    }

    private AuditorIdTransResp getAudotorResp(SurplusInventoryCreateRequest surplusInventoryCreateRequest){
        AuditorIdTransResp auditorIdTransResp=new AuditorIdTransResp();
        auditorIdTransResp.setAuditorIdList1(surplusInventoryCreateRequest.getAuditorIdList1());
        auditorIdTransResp.setAuditorIdList2(surplusInventoryCreateRequest.getAuditorIdList2());
        auditorIdTransResp.setAuditorIdList3(surplusInventoryCreateRequest.getAuditorIdList3());
        return auditorIdTransResp;
    }
}
